import Vuex from 'vuex'
import Vue from 'vue'
import {getPhoneCode,verifyPhoneCode,loginByPhone} from '../api/home/login'
import {Toast} from 'vant'
import router  from '../router/index'

Vue.use(Vuex)

const store = new Vuex.Store({
 
    state:{
        loginInfo:{
            phone:''|| window.localStorage.getItem('phone'),
            
        },
        userInfo:{
            userBaseInfo:null || JSON.parse(window.localStorage.getItem('userInfo')),
            cookie:'' || window.localStorage.getItem('cookie'),
            token:'' || window.localStorage.getItem('token')
        }
    },
    mutations:{
        setPhone(state,phone){
            state.loginInfo.phone = phone
        },
        setUserInfo(state,userInfo){
            state.userInfo.userBaseInfo = userInfo.profile
            window.localStorage.setItem('userInfo',JSON.stringify(userInfo.profile))
            state.userInfo.cookie = userInfo.cookie
            window.localStorage.setItem('cookie',userInfo.cookie)
            state.userInfo.token = userInfo.token
            window.localStorage.setItem('token',userInfo.token)
        }
    },
    actions:{
        // 获取验证码
        async getPhoneCode(context,phone){
            const codeData = await getPhoneCode(phone)
            if(codeData.data.code && codeData.status === 200){
                context.commit('setPhone',phone)
                window.localStorage.setItem('phone',phone)
                Toast('验证码已发送')
                router.push({path:'/getPhoneCode'})
            }else{
                Toast('网络异常，请稍后再试！')
            }
            // console.log(codeData,context)
        },
        // 验证验证码
        async verifyCode(context,verifyInfo){
            const verifData = await verifyPhoneCode(verifyInfo)
            console.log(verifData,context)
            if(verifData.data.code === 200 && verifData.status === 200){
                Toast('登录成功')
                
            }else{
                Toast(verifData.data.message)
            }
        },

        //手机密码验证登录
        async phoneLogin(context,loginInfo){
            const loginResult = await loginByPhone(loginInfo)
            if(loginResult && loginResult.status === 200){
                 Toast('登录成功')
                 context.commit('setUserInfo',loginResult.data)
                 console.log(loginResult)

                 router.go(-1)
            }else{
                Toast(loginResult.data.message)
            }
            // console.log(loginResult)
        }

    },
    getters:{
        
    }
})


export default store